package oboe.controllers;
import haxe.remoting.Connection;
import haxe.remoting.HttpAsyncConnection;
import oboe.core.Oboe;
import oboe.core.SigSlot;
import oboe.core.SigSlotCollection;

/**
 * ...
 * @author Felipe Manga
 */

class ServerConnection extends Translator
{
	private var cnx:HttpAsyncConnection;
	private var signalType:String;
	private var autoPoll:Bool;
	
	public function new( url:String, signalType:String="shortSignal" ) 
	{
		super();
		this.autoPoll = false;
		this.signalType = signalType;
		this.cnx = HttpAsyncConnection.urlConnect(url);
		this.cnx.setErrorHandler( onError );
	}
	
	@slot function autoPollEnabled( e:Bool ):Void
	{
		this.autoPoll = e;
		if( e ) this.message("server_onPoll", []);
	}
	
	private function onError( err )
	{
		Oboe.global.signalDown("onRemotingError", [err]);
	}
	
	override public function _message(name:String, dir:SignalDirection, arguments:Array<Dynamic>):Void 
	{
		if ( StringTools.startsWith( name, "server_" ) )
		{
			#if debug trace("sending server message " + name + "(" + arguments.join(", ") + ")" ); #end
			arguments.push( this.autoPoll );
			cnx.server.message.call( [name.substr("server_".length), arguments], onReturn );
			arguments.pop();
		}
		else
		{
			super._message(name, dir, arguments);
		}
	}
	
	private function onReturn( sigs:Array<Dynamic> ):Void
	{
		for ( sig in sigs )
		{
			#if debug trace( "received server message " + sig.name + "(" + sig.args.join(", ") + ")" ); #end
			Reflect.callMethod( this, Reflect.field( this, this.signalType ), [ sig.name, sig.args ] );
		}
	}
	
}